package com.zzb;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class SendMail {

	public static void sendMail(String tosEmail, String title, String content) {
		String host = "smtp-mail.outlook.com"; // 指定的smtp服务器
		String from = "zhzhbin1030@hotmail.com"; // 邮件标题
		String to = "864141317@qq.com"; // 邮件接收人的邮件地址
		final String username = "zhzhbin1030@hotmail.com"; // 发件人的邮件帐户
		final String password = "54a12326"; // 发件人的邮件密码

		// 创建Properties 对象
		Properties props = System.getProperties();

		// 添加smtp服务器属性 添加了SSL验证
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.user", from);
		props.put("mail.smtp.password", password);
		props.put("mail.smtp.port", "25"); // gmail smtp port 587
		props.put("mail.smtp.auth", "true");

		// 创建邮件会话
		Session session = Session.getDefaultInstance(props,
				new Authenticator() { // 验账账户
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		try {
			// 定义邮件信息
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(MimeUtility.encodeText(from,
					"gb2312", "B")));// GB2312编码，防止接收后标题乱码
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			message.setSubject(title);
			message.setText(content);

			// 发送消息
			// session.getTransport("smtp").send(message); //也可以这样创建Transport对象
			Transport.send(message);

		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SendMail.sendMail("XXXXX@gmail.com", "测试", "发送成功");

	}

}
